package com.zt.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zt.globalExceptionHandler.BizException;
import com.zt.mapper.ClazzMapper;
import com.zt.pojo.Clazz;
import com.zt.pojo.ClazzQuery;
import com.zt.pojo.PageResult;
import com.zt.service.ClazzService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;

    //添加班级
    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(clazz.getCreateTime());
        clazzMapper.add(clazz);
    }

    //查询所有班级
    @Override
    public List<Clazz> findAll() {
        List<Clazz> clazzlist = clazzMapper.findAll();
        return clazzlist;
    }

    //分页查询
    @Override
    public PageResult QueryPage(ClazzQuery clazzQuery) {
        //开启分页
        PageHelper.startPage(clazzQuery.getPage(), clazzQuery.getPageSize());
        //查询
        List<Clazz> clazzList = clazzMapper.QueryPage(clazzQuery);
        Page<Clazz> p = (Page<Clazz>)clazzList;
        return new PageResult(p.getTotal(), p.getResult());
    }

    //根据id删除班级
    @Override
    public void deleteById(Integer id) {
        //先查询该班级下是否存在学生
        Integer num = clazzMapper.findStudentByClazzId(id);
        if(num > 0){
            throw new BizException("该班级下存在学生，无法删除！");
        }else {
            clazzMapper.deleteById(id);
        }
    }

    //根据id查询班级
    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }

    //修改班级
    @Override
    public void update(Clazz clazz) {
        //设置修改时间
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
}
